package com.mtons.mblog.im.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.kisso.security.token.SSOToken;
import com.mtons.mblog.im.common.Constant;
import com.mtons.mblog.im.service.ChatService;
import com.mtons.mblog.im.util.RedisUtil;
import com.mtons.mblog.im.vo.ImMess;
import com.mtons.mblog.im.vo.ImUser;
import com.mtons.mblog.modules.data.AccountProfile;
import com.mtons.mblog.modules.entity.User;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tio.http.common.HttpRequest;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service("chatService")
public class ChatServiceImpl implements ChatService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public String buildSystemMess(Long windowId, String content) {

        Map<Object, Object> sysMess = MapUtil.builder()
                .put("system", true)
                .put("id", windowId)
                .put("type", "group")
                .put("content", content)
                .map();

        return JSONUtil.toJsonStr(sysMess);
    }

    @Override
    public ImUser getCurrentUserInfoFromKisso(SSOToken ssoToken) {

        if(ssoToken == null) {
            //默认用户
            ImUser user = new ImUser();
            user.setAvatar("https://dwz.cn/WC2RCasP");
            user.setId(Constant.DEFAULT_USER_ID);
            user.setSign("匿名~");
            user.setUsername("匿名用户");
            user.setStatus(ImUser.ONLINE_STATUS);
            return user;

        } else {
            Claims claims = ssoToken.getClaims();

            ImUser user = new ImUser();
            user.setId(claims.get("userId", Integer.class).longValue());
            user.setAvatar(claims.get("avatar", String.class));
            user.setUsername(claims.get("username", String.class));
            user.setMine(true);
            user.setStatus(ImUser.ONLINE_STATUS);

            return user;
        }
    }

    /**
     * 所有上线的用户信息：从redis中获取所有上线用户信息
     *
     * @return
     */
    @Override
    public Set<Object> findAllOnlineMembers() {
        Set<Object> ids = redisUtil.sGet(Constant.ONLINE_MEMBERS_KEY);

        Set<Object> results = new HashSet<>();
        if(ids == null) return results;

        ids.forEach((id) -> {

            Map<Object, Object> map = redisUtil.hmget((String) id);
            results.add(map);

        });

        return results;
    }

    /**
     * 获取聊天记录信息
     * @param count
     * @return
     */
    @Override
    public List<Object> getGroupHistoryMsg(int count) {
        long length = redisUtil.lGetListSize(Constant.GROUP_HISTROY_MSG_KEY);
        return redisUtil.lGet(Constant.GROUP_HISTROY_MSG_KEY, length - count < 0 ? 0 : length - count, length);
    }

    /**
     * 设置聊天记录
     * @param imMess
     * @return
     */
    @Override
    public boolean setGroupHistoryMsg(ImMess imMess) {
        return redisUtil.lSet(Constant.GROUP_HISTROY_MSG_KEY, imMess, 24 * 60 * 60);
    }

    /**
     * 记录上线用户信息
     * @param httpRequest
     * @return
     */
    @Override
    public boolean putOnlineMember(HttpRequest httpRequest, AccountProfile user){

        String username = user.getName();
        String userId = user.getId()+"";
        String avatar = user.getAvatar();
        /*String username = httpRequest.getParam("username");
        String userId = httpRequest.getParam("userId");
        String avatar = httpRequest.getParam("avatar");*/


        Map<String, Object> member = MapUtil.builder("id", (Object)userId)
                .put("username", username)
                .put("avatar", avatar)
                .map();
        redisUtil.hmset("members:" + userId, member);

        return redisUtil.sSet(Constant.ONLINE_MEMBERS_KEY, "members:" + userId) > 0;
    }

    /**
     * 清除用户信息
     * @param userid
     */
    @Override
    public void popOutlineMember(String userid) {
        redisUtil.setRemove(Constant.ONLINE_MEMBERS_KEY, "members:" + userid);
    }
}
